package com.tzsafe.nfcdemo

import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.Gravity
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.hjq.toast.ToastUtils
import com.kongzue.dialogx.dialogs.InputDialog
import com.kongzue.dialogx.dialogs.MessageDialog
import com.kongzue.dialogx.interfaces.OnDialogButtonClickListener
import com.tzsafe.nfcdemo.databinding.ActivityUserListBinding
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.security.MessageDigest
import java.text.SimpleDateFormat
import java.util.Date
//import okhttp3.Call
//import okhttp3.Callback
//import okhttp3.FormBody
//import okhttp3.OkHttpClient
//import okhttp3.Request
//import okhttp3.Response
//import okio.IOException
//import java.security.MessageDigest
//import java.text.SimpleDateFormat
//import java.util.Date
import kotlin.random.Random

class UserListActivity : AppCompatActivity() {
    var userListData = ArrayList<UserInfo>()
    private val userAdapter: UserAdapter by lazy { UserAdapter() }
    private lateinit var mBind: ActivityUserListBinding
    private var system_code: String = ""
    private var queryListData: List<UserInfo> = emptyList()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mBind = ActivityUserListBinding.inflate(layoutInflater)
        setContentView(mBind.root)

        val titlem = intent.getStringExtra("title")
        if (title != null) {
            supportActionBar?.title = titlem
        } else {

            supportActionBar?.apply {
                setDisplayHomeAsUpEnabled(true)
                title = "请选择机构名称"
            }
        }

        //初始化 recycleView
        mBind.listRecyclerView.grid(1).divider {
            orientation = DividerOrientation.GRID
            includeVisible = true
            setDivider(1, true)
        }.adapter = userAdapter

        val userListDataString = mmkv.getString(ValueKey.USER_INFO_KEY, "")
        if (!userListDataString.isNullOrEmpty()) {
            val listData = Gson().fromJson<Any>(
                userListDataString.toString(), object : TypeToken<ArrayList<UserInfo>>() {}.type
            ) as ArrayList<UserInfo>
            Log.e("测试", "缓存的bean数据 " + listData.toString())
            userListData.clear()
            userListData = listData
            userAdapter.setNewData(userListData)
            userAdapter.notifyDataSetChanged()
        }

        userAdapter.setOnItemClickListener { adapter, view, position ->
            confirmOrganizationSelection(position)
        }
        getDataList()

//        mBind.searchET.setOnClickListener {
//            mBind.searchET.isCursorVisible = true
//            mBind.searchET.requestFocus()
//        }

        mBind.searchET.setOnFocusChangeListener { _, hasFocus ->
            mBind.searchET.isCursorVisible = true
        }

        mBind.searchET.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                if (!s.isNullOrEmpty()) {
                    val contentString = mBind.searchET.text.toString().trim()

                    queryListData = userListData.filter { it.name.contains(contentString) }
                    Log.e("测试", "筛选后的结果 " + queryListData.toString())
                    userAdapter.setNewData(queryListData)
                    userAdapter.notifyDataSetChanged()
                } else {
                    val contentString = mBind.searchET.text.toString().trim()
                    queryListData = userListData.filter { it.name.contains(contentString) }
                    Log.e("测试", "筛选后的结果 " + queryListData.toString())

                    userAdapter.setNewData(userListData)
                    userAdapter.notifyDataSetChanged()
                }
            }

            override fun afterTextChanged(s: Editable?) {}
        })
    }

    private fun getDataList() {
        RetrofitClient.instance.getListData(getToken())
            .enqueue(object : Callback<ApiResponse<ArrayList<UserInfo>>> {
                override fun onResponse(
                    call: Call<ApiResponse<ArrayList<UserInfo>>>,
                    response: Response<ApiResponse<ArrayList<UserInfo>>>
                ) {
                    if (response.isSuccessful) {
                        Log.e("测试", "请求成功 " + response.body())
                        if (response.body()?.code == "08") {
                            userListData.clear()
                            userListData = response.body()!!.data
//                            for (i in 0 until userListData.size){
//                                Log.e("测试","请求数据 "+userListData[i])
//                            }
                            userAdapter.setNewData(userListData)
                            userAdapter.notifyDataSetChanged()
                            mmkv.putString(ValueKey.USER_INFO_KEY, Gson().toJson(userListData))
                        } else {
                            ToastUtils.show(response.body()?.info)
                        }
                    } else {
                        Log.e("测试", "请求成功 " + response.errorBody()?.string())
                    }
                }

                override fun onFailure(call: Call<ApiResponse<ArrayList<UserInfo>>>, t: Throwable) {
                    Log.e("测试", "请求成功 " + t.message)
                }
            })
    }

    fun getToken(): String {
        val sKey = "Tazan@85271383" + SimpleDateFormat("yyyyMMdd").format(Date())
        val currentToken = md5(sKey).toUpperCase()
        return currentToken
    }

    // MD5 计算辅助函数
    fun md5(input: String): String {
        val md = MessageDigest.getInstance("MD5")
        val digest = md.digest(input.toByteArray())
        return digest.fold("") { str, it -> str + "%02x".format(it) }
    }

//    private fun confirmOrganizationSelection(position: Int, name: String) {
//        var inputDialog = InputDialog(
//            "确认选择该机构吗？", name, "确定", "取消"
//        ).setInputHintText("请输入密码").setAutoShowInputKeyboard(false)
//            .setInputText("")
//            .setOkButton { baseDialog, v, inputStr ->
//                if (inputStr.isNullOrEmpty()) {
//                    ToastUtils.show("密码不能为空")
//                } else {
//                    //自行判断密码是否匹配的,假设匹配成功
//                    userListData.removeAt(position)
//                    userAdapter.setNewData(userListData)
//                    userAdapter.notifyDataSetChanged()
//                    mmkv.putString(ValueKey.USER_INFO_KEY, Gson().toJson(userListData))
//                }
//
//                false
//            }
//        inputDialog.show()
//    }

    private fun confirmOrganizationSelection(position: Int) {
        var OrganizationName: String = ""
        var code: String = ""
        if (queryListData.size == 0) {
            OrganizationName = userListData[position].name
            code = userListData[position].system_code
        } else {
            OrganizationName = queryListData[position].name
            code = queryListData[position].system_code
        }
        // 创建一个居中的 TextView
        val messageView = TextView(this).apply {
            text = OrganizationName
            gravity = Gravity.CENTER
            textSize = 28f // 可选：调整字体大小
            setPadding(0, 20, 0, 20) // 可选：调整上下间距
        }

        AlertDialog.Builder(this)
            .setTitle("确认选择该机构吗？")
            .setView(messageView) // 使用自定义 TextView 替代 setMessage
            .setPositiveButton("确定") { dialog, _ ->
                supportActionBar?.title = OrganizationName
                system_code = code

                // 关闭光标
                mBind.searchET.isCursorVisible = false
                // 清除焦点，防止键盘继续显示
                mBind.searchET.clearFocus()
                mBind.searchET.text.clear()
                queryListData = emptyList()
                userAdapter.setNewData(userListData)
                userAdapter.notifyDataSetChanged()

                dialog.dismiss()
            }
            .setNegativeButton("取消") { dialog, _ ->
                dialog.dismiss()
            }
            .setCancelable(true)
            .show()
    }

    override fun onBackPressed() {
        if (system_code.isNullOrEmpty()) {
            val foundUser = userListData.find { it.name == supportActionBar?.title }
            if (foundUser != null) {
                system_code = foundUser.system_code
            }
        }
        val resultIntent = Intent().apply {
            putExtra("title", supportActionBar?.title?.toString() ?: "") // 回传 title
            putExtra("system_code", system_code) // 回传 pwd
        }
        setResult(RESULT_OK, resultIntent) // 设置返回结果
        finish() // 关闭当前 Activity
    }

    fun getRandomPassWord(): String {
        val hexChars = "0123456789ABCDEF"
        return (1..64)
            .map { hexChars[Random.nextInt(hexChars.length)] }
            .joinToString("")
    }
}
